<?php

namespace app\common\model\logic;

use Firebase\JWT\JWT;

class JwtModel
{
    private $key;

    public function __construct()
    {
        $this->key = 'lxkj828-jwt-key';
    }

    //生成token
    public function generateToken($data)
    {
        $payload = [
            'iss' => 'lxkj_api', //签发人
            'aud' => 'all', //受众
            'data' => $data, //数据
            'iat' => time(), //签发时间
            'nbf' => time(), //生效时间
            'exp' => time() + 36000, //过期时间
        ];

        return JWT::encode($payload, $this->key);
    }

    //获取token数据
    public function getPayload()
    {
        $token = request()->header('Authorization');
        if (empty($token)) {
            exception('没有设置token', 2, 'app\\common\\exception\\TokenException');
        }
        try {
            $decoded = (array) JWT::decode($token, $this->key, ['HS256']);
        } catch (\Exception $e) {
            exception('token无效，请重新登录', 2, 'app\\common\\exception\\TokenException');
        }
        if ($decoded['exp'] < time()) {
            exception('token失效，请重新登录', 2, 'app\\common\\exception\\TokenException');
        }

        return  $decoded['data'];
    }

    //验证token
    public function checkToken($token)
    {
        $requsrtToken = request()->header('Authorization');
        if ($requsrtToken !== $token) {
            exception('token已失效，请重新登录', 2, 'app\\common\\exception\\TokenException');
        }

        return  true;
    }
}
